package com.wwj.auction.login.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wwj.auction.common.constant.SystemConstant;
import com.wwj.auction.common.entity.Address;
import com.wwj.auction.common.entity.Cities;
import com.wwj.auction.common.entity.Counties;
import com.wwj.auction.common.util.AddressUtils;
import com.wwj.auction.common.util.MD5;
import com.wwj.auction.login.entity.UserAccount;
import com.wwj.auction.login.entity.UserAddress;
import com.wwj.auction.login.entity.UserInfo;
import com.wwj.auction.login.entity.vo.SimpleUserInfoVo;
import com.wwj.auction.login.entity.vo.UserInfoVo;
import com.wwj.auction.login.mapper.UserAccountMapper;
import com.wwj.auction.login.mapper.UserAddressMapper;
import com.wwj.auction.login.mapper.UserInfoMapper;
import com.wwj.auction.login.service.UserInfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wwj
 * @since 2021-08-10
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Resource
    private UserAddressMapper userAddressMapper;
    @Resource
    private UserAccountMapper userAccountMapper;

    @Override
    public boolean isRegistered(String phone) {
        LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserInfo::getPhone, phone);
        UserInfo userInfo = baseMapper.selectOne(wrapper);
        System.out.println(userInfo);
        return userInfo != null;
    }

    @Override
    public void register(UserInfo userInfo) {
        // 新注册用户开店状态为0（未开店）
        userInfo.setStoreStatus(0);
        baseMapper.insert(userInfo);
    }

    @Override
    public UserInfo checkUser(UserInfo userInfo) {
        String phone = userInfo.getPhone();
        String password = userInfo.getPassword();
        // 对密码进行MD5加密
        String encryptPwd = MD5.encrypt(password);
        return baseMapper.selectOne(
                new LambdaQueryWrapper<UserInfo>()
                        .eq(UserInfo::getPhone, phone)
                        .and(wrapper -> wrapper.eq(UserInfo::getPassword, encryptPwd)));

    }

    @Override
    public UserAddress findAddressInfo(List<Integer> addressList) {
        // 获取地区的原始json数据
        String addressJson = AddressUtils.getOriginalData();
        // 将json转为集合
        List<Address> list = JSONObject.parseObject(addressJson, new TypeReference<List<Address>>() {
        });
        UserAddress userAddress = new UserAddress();
        // 从集合中找出具体的地区信息并封装成实体
        for (Address address : list) {
            if (Objects.equals(address.getProvinceCode(), String.valueOf(addressList.get(SystemConstant.ADDRESS_PROVINCE_INDEX)))) {
                userAddress.setProvince(address.getProvinceName());
                // 从省份中获取市信息
                List<Cities> cities = address.getCities();
                for (Cities city : cities) {
                    if (Objects.equals(city.getCityCode(), String.valueOf(addressList.get(SystemConstant.ADDRESS_CITY_INDEX)))) {
                        userAddress.setCity(city.getCityName());
                        // 从市中获取县信息
                        List<Counties> counties = city.getCounties();
                        for (Counties county : counties) {
                            if (Objects.equals(county.getCountyCode(), String.valueOf(addressList.get(SystemConstant.ADDRESS_COUNTY_INDEX)))) {
                                userAddress.setCounty(county.getCountyName());
                                break;
                            }
                        }
                        break;
                    }
                }
                break;
            }
        }
        return userAddress;
    }

    @Override
    public void updateUserInfo(UserInfoVo userInfoVo, UserAddress userAddress) {
        Integer addressId;
        // 查询当前地址是否已经存储
        UserAddress address = userAddressMapper.selectOne(
                new LambdaQueryWrapper<UserAddress>()
                        .eq(UserAddress::getProvince, userAddress.getProvince())
                        .eq(UserAddress::getCity, userAddress.getCity())
                        .eq(UserAddress::getCounty, userAddress.getCounty()));
        if (address == null) {
            // 插入地址信息
            userAddressMapper.insert(userAddress);
            addressId = userAddress.getId();
        } else {
            addressId = address.getId();
        }
        // 通过手机号查询得到当前的用户id
        String phone = userInfoVo.getPhone();
        UserInfo userInfo = baseMapper.selectOne(new QueryWrapper<UserInfo>().eq("phone", phone));
        // 将前端传递过来的用户信息拷贝到查询出来的实体中
        BeanUtils.copyProperties(userInfoVo, userInfo);
        // 设置地址信息的主键id
        userInfo.setAddress(addressId);
        System.out.println(userInfo);
        // 更新用户信息
        baseMapper.updateById(userInfo);
    }

    @Override
    public SimpleUserInfoVo getUserInfo(Long userId) {
        // 根据id查询用户
        UserInfo userInfo = baseMapper.selectOne(
                new LambdaQueryWrapper<UserInfo>()
                        .eq(UserInfo::getId, userId));
        SimpleUserInfoVo simpleUserInfoVo = new SimpleUserInfoVo();
        simpleUserInfoVo.setName(userInfo.getNickName());
        // 设置绑定状态
        simpleUserInfoVo.setBindStatus(userInfo.getBindStatus());
        // 查询账户余额与冻结金额
        UserAccount userAccount = userAccountMapper.selectOne(
                new LambdaQueryWrapper<UserAccount>()
                        .eq(UserAccount::getPhone, userInfo.getPhone()));
        simpleUserInfoVo.setAmount(userAccount.getAmount());
        simpleUserInfoVo.setFreezeAmount(userAccount.getFreezeAmount());
        // 设置最近登录时间
        LocalDateTime loginTime = userInfo.getLoginTime();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        simpleUserInfoVo.setLoginTime(loginTime.format(dateTimeFormatter));
        return simpleUserInfoVo;
    }

    @Override
    public void updateLoginTime(String phone) {
        // 通过手机号查询当前用户
        UserInfo userInfo = baseMapper.selectOne(
                Wrappers.lambdaQuery(UserInfo.class)
                        .eq(UserInfo::getPhone, phone));
        userInfo.setLoginTime(LocalDateTime.now());
        // 更新
        baseMapper.updateById(userInfo);
    }

    @Override
    public Integer getUserType(String phone) {
        UserInfo userInfo = baseMapper.selectOne(
                Wrappers.lambdaQuery(UserInfo.class)
                        .eq(UserInfo::getPhone, phone));
        return userInfo.getUserType();
    }

    @Override
    public Integer getStoreStatus(Long userId) {
        UserInfo userInfo = baseMapper.selectOne(
                Wrappers.lambdaQuery(UserInfo.class)
                        .eq(UserInfo::getId, userId));
        return userInfo.getStoreStatus();
    }
}
